<script setup lang="tsx">
import { onMounted, reactive, ref, watch } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElCheckbox, ElInput, ElLink, ElMessage } from 'element-plus'
import { useForm } from '@/hooks/web/useForm'
import { loginApi, getTestRoleApi, getAdminRoleApi, imgcdeApi, getRouters } from '@/api/login'
import { useStorage } from '@/hooks/web/useStorage'
import { useAppStore } from '@/store/modules/app'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import { UserType } from '@/api/login/types'
import { useValidator } from '@/hooks/web/useValidator'
import CryptoJS from 'crypto-js';
import { Icon } from '@/components/Icon'
import logoImage from '@/assets/imgs/logo.png'
import { TurnOff } from '@element-plus/icons-vue/dist/types'
import routerTable from '@/router/table'
const { required } = useValidator()

const emit = defineEmits(['to-register'])

const appStore = useAppStore()

const permissionStore = usePermissionStore()

const { currentRoute, addRoute, push } = useRouter()

const { setStorage } = useStorage()

const { t } = useI18n()
const state = reactive({
  ruleForm: {
    code: ""
  } as any,
  form: {
    session_id: "" as any,
    keycode: "",
    username: "",
    password: "",
    uuid: ""
  } as any,
  encryptedDatapassword: "",
  encryptedDatausername: "",
  decryptedDatapassword: "",
  decryptedDatausername: "",
})
const rules = {
  username: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^[1][3,4,5,7,8,9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    // { pattern: /^[A-Za-z0-9]+$/, message: '密码只能包含英文字母和数字', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur', },
  ]
}
// 解密密码  
const decryptPassword = () => {
  let password: any = localStorage.getItem("password") ? localStorage.getItem("password") : ""
  if (password) {
    password = JSON.parse(password)
    const bytes = CryptoJS.AES.decrypt(password, 'mySecretKey');
    const originalPassword = bytes.toString(CryptoJS.enc.Utf8);
    return originalPassword
  } else {
    return ""
  }


};
// 加密密码  
const encryptPassword = (message) => {
  const maskedPassword = CryptoJS.AES.encrypt(message, 'mySecretKey').toString();
  localStorage.setItem("password", JSON.stringify(maskedPassword))
};
const schema = reactive<FormSchema[]>([
  {
    field: 'Login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <div>
            <h2 class="login-text2  w-[100%]">香城英才网</h2>
            {/* <h2 class="login-text3  w-[100%]">Human Resources Management System</h2> */}
          </div>
        }
      }
    }
  },
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="text-2xl font-bold  w-[100%]">管理员登录</h2>
        }
      }
    }
  },
  {
    field: 'username',
    label: "",
    value: localStorage.getItem('username') ? localStorage.getItem('username') : '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: "请输入手机号"
    }
  },
  {
    field: 'password',
    label: "",
    value: decryptPassword() ? decryptPassword() : '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      placeholder: "请输入用户密码"
    }
  },
  {
    field: 'code',
    label: "",
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div class="flex imagecodes-main">
                <el-form class="demo-ruleForm">
                  <el-form-item prop="code">
                    <ElInput placeholder='请输入验证码' v-model={data.code} type='number'></ElInput>
                  </el-form-item>
                </el-form>
                <img class="imagecodes" src={imagecode.value} onClick={() => actionFn()}></img>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex justify-between items-center w-[100%]">
                <ElCheckbox v-model={remember.value} label={t('记住账号密码')} size="small" />
                <ElLink type="primary" underline={false} onClick={toForget}>
                  {t('login.forgetPassword') + "?"}
                </ElLink>
              </div>
            </>
          )
        }
      }
    }
  },

  {
    field: 'login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <ElButton loading={loading.value} type="primary" class="w-[100%]" onClick={() => signIn()}>
                  {t('login.login')}
                </ElButton>
              </div>
              {/* <div class="w-[100%] mt-15px flex justify-center items-center">
                <ElLink type="primary" underline={false} onClick={toRegister}>还没有账号?去注册</ElLink>
              </div> */}
            </>
          )
        }
      }
    }
  }

])

const remember = ref(true)
const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods
const loading = ref(false)
const redirect = ref<string>('')
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// 登录-环境
const signIn = async () => {

  const formRef = await getElFormExpose()
  await formRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const formData = await getFormData<UserType>()
      state.form.username = formData.username
      state.form.password = formData.password
      state.form.keycode = formData.code
      let params = {
        "clientId": "e5cd7e4891bf95d1d19206ce24a7b32e",
        "clientKey": "",
        "clientSecret": "",
        "grantType": "phonePassword",
        "tenantId": "000000",
        "username": "",
        "password": state.form.password,
        "code": state.form.keycode,
        "uuid": state.form.uuid,
        "phonenumber": state.form.username,
        "smsCode": "",
        "email": "",
        "emailCode": "",
        "xcxCode": "",
        "source": "",
        "socialCode": "",
        "socialState": ""
      }
      try {
        const res: any = await loginApi(params)
        if (res) {
          if (remember.value) {
            localStorage.setItem('username', formData.username);
            encryptPassword(formData.password)
          } else {
            localStorage.removeItem('username');
            localStorage.removeItem('password');
          }
          loading.value = false
          ElMessage.success(res.msg)
          setStorage(appStore.getUserInfo, res.data)
          // 是否使用动态路由
          console.log("使用动态路由", appStore.getDynamicRouter);
          let bool = false
          if (state.form.username == '15847339539') {
            bool = true
          } else {
            bool = true
          }
          if (bool) {
            getRole()
          } else {
            console.log("登录配置！！！！！");
            await permissionStore.generateRoutes('none').catch(() => { })
            permissionStore.getAddRouters.forEach((route) => {
              addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
            })
            permissionStore.setIsAddRouters(true)
            push({ path: redirect.value || permissionStore.addRouters[0].path })
          }

        }
      } finally {
        loading.value = false
      }
    }
  })
}






// 获取角色信息
const getRole = async () => {
  // const formData = await getFormData<UserType>()
  // const params = {
  //   roleName: formData.username
  // }
  // // admin - 模拟后端过滤菜单
  // // test - 模拟前端过滤菜单
  // const res =
  //   formData.username === 'admin' ? await getAdminRoleApi(params) : await getTestRoleApi(params)
  const res = await getRouters()
  console.log("后端传来的路由表：", res);

  if (res) {
    const routers = res.data || []
    let routerTables = routerTable
    routerTables=routerTables.concat(routerTableFun(routers))
    const count = countElementsWithChar(routerTables, "/dictionary");
    if(count==1){
      removeElement(routerTables, "/dictionary")
    }
    console.log("路由表：", routerTables);
    setStorage('roleRouters', routerTables)
    await permissionStore.generateRoutes('test', routerTables).catch(() => { })
    permissionStore.getAddRouters.forEach((route) => {
      addRoute(route as RouteRecordRaw) // 动态添加可访问路由表
    })
    permissionStore.setIsAddRouters(true)
    push({ path: redirect.value || permissionStore.addRouters[0].redirect })
  }
}
function removeElement(arr, element) {
  const index = arr.indexOf(element);
  if (index > -1) {
    arr.splice(index, 1);
  }
  
}
function countElementsWithChar(arr, charToFind) {
  return arr.filter(element => element.includes(charToFind)).length;
}
function routerTableFun(data: any) {
  let arrays = [] as any
  data.forEach(element => {
    arrays.push(element.path)
    if (element.children && element.children.length != 0) {
      let arr=[]
      arr=routerTableFun(element.children)
      arrays=[...arrays,...arr]
    }
  });
  
  
  return arrays
}

// 图片地址
const imagecode: any = ref("")
const codeValue: any = ref(false)
const actionFn = () => {
  imgcdeApi_()
}
// 获取imagecode
const imgcdeApi_ = async () => {
  // codeValue.value = false
  let params = Math.floor(Math.random() * 10000)
  state.form.session_id = params
  await imgcdeApi(params).then((res) => {
    imagecode.value = "data:image/jpeg;base64," + res.data.img
    state.form.uuid = res.data.uuid
    // codeValue.value = true
    // console.log(res);
  })
}
imgcdeApi_()
// 去注册页面
const toRegister = () => {
  emit('to-register')
}
const toForget = () => {
  emit('to-forget')
}
</script>

<template>
  <div class="login_content">
    <Form :schema="schema" :rules="rules" label-position="top" hide-required-asterisk size="large"
      class="dark:(border-1 border-[var(--el-border-color)] border-solid)" @register="formRegister" />
    <!-- <div class="beian">备案号：</div> -->
  </div>
</template>
<style lang="less" >
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

.login_content {
  position: relative;

  .beian {
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 0px;
    color: gray;
  }
}

input[type='number'] {
  -moz-appearance: textfield;
}

.imagecodes-main {
  width: 100%;
  justify-content: space-between;
}

.imagecodes {
  width: 120px;
  height: 40px;
  margin-left: 15px;
}

h2 {
  margin: 0px;
}

.login-text2 {
  font-size: 34px;
  font-family: 'HarmonyOS Sans SC-Bold, HarmonyOS Sans SC';
  font-weight: 700;
  color: #2F6CBC;
  // line-height: 41px;
}

.login-text3 {
  font-size: 16px;
  font-family: 'HarmonyOS Sans SC-Bold, HarmonyOS Sans SC';
  font-weight: 400;
  color: #3D3D3D;
  // line-height: 41px;
}

.login-images {
  width: 72px;
  height: 74px;

  img {
    width: 100%;
    height: 100%;
  }
}
</style>
